package com.zxy.ider.ehome;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.zxy.ider.ehome.View.TitleTextView;
import com.zxy.ider.ehome.View.TvGridView;
import com.zxy.ider.ehome.adapter.FileAdapter;
import com.zxy.ider.ehome.applist.AppListActivity;
import com.zxy.ider.ehome.bean.MyFile;
import com.zxy.ider.ehome.bean.Sms;
import com.zxy.ider.ehome.db.UpInfo;
import com.zxy.ider.ehome.file.FileControl;
import com.zxy.ider.ehome.util.FileUtils;
import com.zxy.ider.ehome.util.NetUtil;
import com.zxy.ider.ehome.util.PreferenceManager;
import com.zxy.ider.ehome.util.SendInfo;
import com.zxy.ider.ehome.util.TvUtil;

import org.litepal.crud.DataSupport;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;

public class FileActivity extends Activity {
    private String dateurl;
    private String title;
    private GridView tvgrid;
    private ImageView back_bt,down_bt;
    private List<MyFile> files;
    private String currentPath="";
    private FileAdapter adapter;
    private TitleTextView titleName,fileTotal;
    private String fileTotaltext = "1/60";
    private String startTime;
    private String playName;
    private String logoAddress;
    private boolean playing = false;
    private boolean isOpen = false;
    Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
        Intent intent = getIntent();
        dateurl = intent.getStringExtra("dataUrl");
        title = intent.getStringExtra("title");
        logoAddress = intent.getStringExtra("logoAddress");
        initview();
        files = getFileDir(dateurl);
        titleName.setText(title);
        if(files!=null&&files.size()>=0){
            currentPath = dateurl;
            adapter = new FileAdapter(files);
            tvgrid.setAdapter(adapter);
            fileTotaltext = "1/"+files.size();
            setFoces();

        }else{
            File file = new File(dateurl);
            if(!file.exists()){
                Toast.makeText(FileActivity.this,"文件目录不存在",Toast.LENGTH_SHORT).show();
            }
        }
        mksaveDir();
        setListener();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(mHomeKeyEventReceiver, filter);
    }
    private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {
        String SYSTEM_REASON = "reason";
        String SYSTEM_HOME_KEY = "homekey";
        String SYSTEM_HOME_KEY_LONG = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_REASON);
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {
                    //表示按了home键,程序到了后台
                    saveFile();
                    FileActivity.this.finish();
                }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){
                    //表示长按home键,显示最近使用的程序列表
                    saveFile();
                    FileActivity.this.finish();
                }
            }
        }
    };

    private void initview() {
        tvgrid = (GridView) findViewById(R.id.file_Grid);
        tvgrid.getBackground().setAlpha(50);
        back_bt = (ImageView) findViewById(R.id.back_bt);
        down_bt = (ImageView) findViewById(R.id.down_bt);
        titleName = (TitleTextView) findViewById(R.id.titleName);
        fileTotal = (TitleTextView) findViewById(R.id.fileTotal);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            Log.i("zxy", "onKeyDown: currentPath="+currentPath);
            if(currentPath.length()>dateurl.length()){
                currentPath = currentPath.substring(0,currentPath.lastIndexOf("/"));
                files.clear();
                files = getFileDir(currentPath);
               // tvgrid.removeAllViews();
                adapter = new FileAdapter(files);
                tvgrid.setAdapter(adapter);
                fileTotaltext = "1/"+files.size();
                setFoces();
                title = title.substring(0,title.lastIndexOf("/"));
                titleName.setText(title);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setListener(){
        tvgrid.setOnItemClickListener(new GridView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                MyFile mfile = files.get(position);
                if(mfile.isDirectory()){
                    if(files!=null&&files.size()>0){
                        currentPath = mfile.getAbsolutePath();
                        files.clear();
                        files = getFileDir(mfile.getAbsolutePath());
                       // tvgrid.removeAllViews();
                        adapter = new FileAdapter(files);
                        tvgrid.setAdapter(adapter);
                        fileTotaltext = "1/"+files.size();
                        setFoces();
                        title = title+"/"+mfile.getFileName();
                        titleName.setText(title);
                    }
                }else{
                    openFile(mfile);
                }
            }

        });
        tvgrid.setOnItemSelectedListener(new GridView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
                fileTotaltext = (position+1)+"/"+files.size();
                fileTotal.setText(fileTotaltext);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }

        });
    }
    public List<MyFile> getFileDir(String path){
       File fileparent = new File(path);
       if(fileparent.exists()){
           files = new ArrayList<MyFile>();
           MyFile myfie = null;
           if(fileparent.isDirectory()){
              File[] filesRoot =fileparent.listFiles();
               for (int i = 0 ;i <  filesRoot.length;i++){
                       myfie = doMyfile(filesRoot[i].getAbsolutePath());
                       files.add(myfie);
                   }
                   orderByName(files);//排序---数字-字母--中文
               return files;
           }
           return null;
       }
        return null;
    }

    public void orderByName(List<MyFile> files) {
        Collections.sort(files, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile())
                    return -1;
                if (o1.isFile() && o2.isDirectory())
                    return 1;
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    @Override
    protected void onDestroy() {
        try{
            unregisterReceiver(mHomeKeyEventReceiver);
        }catch (Exception e){

        }
        super.onDestroy();
    }
    /**
     * 打开文件
     * @param file
     */
    private void openFile(MyFile file){
        //Uri uri = Uri.parse("file://"+file.getAbsolutePath());
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
        //获取文件file的MIME类型
        String type =file.getType();
        //设置intent的data和Type属性。
        intent.setDataAndType(/*uri*/Uri.fromFile(file), type);
        startTime = System.currentTimeMillis()+"";
        playName = file.getAbsolutePath();
        if(type.contains("video")){
            playing = true;
            isOpen = false;
            intent.setPackage("com.droidlogic.videoplayer");
            intent.putExtra("logoAddress",logoAddress);
            startActivity(intent);
        }else{
            playing=false;
            isOpen = true;
            openOtherFile(file);
        }
        //跳转

    }
    private void openOtherFile(File file){
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.putExtra("logoAddress",logoAddress);
        String type = FileControl.getMIMEType(file);
        Log.d("zhao","===openOtherFile type==="+type);
        Uri uri= Uri.fromFile(file);
        intent.setDataAndType(uri, type);
        try {
            startActivity(intent);
        } catch (android.content.ActivityNotFoundException e) {
            Toast.makeText(FileActivity.this, getString(R.string.noapp), Toast.LENGTH_SHORT).show();
           e.printStackTrace();
        }

    }
    @Override
    protected void onResume() {
        saveFile();
        super.onResume();
    }
    private void saveFile(){
        if(playing){
            playing=false;
            Log.i("zxy", "onResume: start save file");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveUserPlay(playName,startTime,true);
                }
            }).start();
        }
        if(isOpen){
            isOpen=false;
            Log.i("zxy", "onResume: start save file");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveUserPlay(playName,startTime,false);
                }
            }).start();
        }
    }

    public MyFile doMyfile(String path){
        File file = new File(path);
        if(!file.exists()){
            return null;
        }
        MyFile myFile = null;
        if(file.isDirectory()){
            myFile = new MyFile(path,getFiletyPe(R.mipmap.file_type_file) ,
                    file.getName(),null,true,"dirs");
        }else{
            String type = FileUtils.getMIMEType(file);
            Drawable filetypeIcon = null;
            if( type.contains("video")){
                filetypeIcon = getFiletyPe(R.mipmap.file_type_video);
            }else if(type.contains("audio")){
                filetypeIcon = getFiletyPe(R.mipmap.file_type_music);
            }else if(type.contains("image")){
                filetypeIcon = getFiletyPe(R.mipmap.file_type_picture);
            }else if(type.contains("txt")){
                filetypeIcon = getFiletyPe(R.mipmap.file_type_txt);
            }else if(type.contains("application/vnd.android.package-archive")){
                filetypeIcon = getFiletyPe(R.mipmap.file_type_apk);
            }else if(type.contains("application/x-tar")||type.contains("application/x-compressed")
                    ||type.contains("application/zip")||type.contains("application/x-tar")||
                    type.contains("application/x-rar-compressed")){
                filetypeIcon = getFiletyPe(R.mipmap.file_type_zip);
            }else if(type.contains("application/pdf")){
                filetypeIcon = getFiletyPe(R.mipmap.file_type_pdf);
            }else if(type.contains("text/html")){
                filetypeIcon = getFiletyPe(R.mipmap.file_type_html);
            }else{
                filetypeIcon = getFiletyPe(R.mipmap.file_type_null);
            }
            myFile = new MyFile(path,filetypeIcon,
                    file.getName(),FileUtils.fileSizeMsg(file),false,type);
        }
        return myFile;
    }

    private Drawable getFiletyPe(int id ){
        return Appcontext.getAppContext().getDrawable(id);
    }

    public void btOnclick(View view){
        if(view.getId()==R.id.back_bt){
            if(null!=files&&currentPath.length()>dateurl.length()){
                currentPath = currentPath.substring(0,currentPath.lastIndexOf("/"));
                files.clear();
                files = getFileDir(currentPath);
               // tvgrid.removeAllViews();
                adapter = new FileAdapter(files);
                tvgrid.setAdapter(adapter);
                fileTotaltext = "1/"+files.size();
                setFoces();
                title = title.substring(0,title.lastIndexOf("/"));
                titleName.setText(title);
            }else{
                FileActivity.this.finish();
            }
        }else if(view.getId()==R.id.down_bt){

            if(null!=files&&!TvUtil.isFastDoubleClick()) {
                    tvgrid.smoothScrollToPosition(files.size());
                tvgrid.setSelection(files.size()-1);
            }
        }
    }

    public void setFoces(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(tvgrid.getChildAt(0)!=null){
                    tvgrid.getChildAt(0).requestFocus();
                    fileTotal.setText(fileTotaltext);
                }
            }
        },400);
    }

    public void mksaveDir(){
        File cacheFolder = new File(Constant.APK_CACHE_PATH);
        if (!cacheFolder.exists()) {
            Log.i("zxy", "openItem: file not exit");
            boolean s1 = cacheFolder.mkdirs();
            Log.i("zxy", "openItem: file =" + cacheFolder.exists() + s1);
        }
    }

    public void saveUserPlay(String path,String startTime,boolean isVideo){
        final PreferenceManager pm = PreferenceManager.getInstance(FileActivity.this);
        Log.i("zxy", "saveUserPlay: save backup.xml");
        String endtime = System.currentTimeMillis()+"";
        //String mac = NetUtil.getLocalEthernetMacAddress();
        //String mac = "dc:c0:db:97:f1:5d";

        String playerTyper = "player2";
        String userType = "video";
        String uservalue= path;
        String userIp = getHostIP();
        UpInfo upInfoing;
        if (isVideo){
            upInfoing = new UpInfo(Constant.mac,Build.MODEL,userType,uservalue,startTime,endtime);
        }else {
            upInfoing = new UpInfo(Constant.mac, Build.MODEL,path,startTime);
        }
        final UpInfo upInfo = upInfoing;

//        Sms sms = new Sms(sendtime,mac,checkcode,playerTyper,userType,uservalue,startTime,sendtime,userIp);
        File file = new File(Constant.APK_CACHE_PATH,
                "backup.xml");
        try {
//            FileOutputStream fos = new FileOutputStream(file);
//            StringBuffer sb = new StringBuffer();
//            // 添加xml头
//            sb.append("<?xml version='1.0' encoding='utf-8' standalone='yes' ?>");
//            // 添加根节点
//            sb.append("<item>");
//            sb.append("<checktext>");
//            sb.append("<sendtime>");
//            sb.append(sms.getSendtime());
//            sb.append("</sendtime>");
//            sb.append("<MAC>");
//            sb.append(sms.getMac());
//            sb.append("</MAC>");
//            sb.append("<checkcode>");
//            sb.append(sms.getCheckcode());
//            sb.append("</checkcode>");
//            sb.append("</checktext>");
//
//            sb.append("<record>");
//            sb.append("<post>");
//
//            sb.append("<Playertype>");
//            sb.append(sms.getPlayertype());
//            sb.append("</Playertype>");
//
//            sb.append("<MAC>");
//            sb.append(sms.getMac());
//            sb.append("</MAC>");
//
//            sb.append("<Usetype>");
//            sb.append(sms.getUsetype());
//            sb.append("</Usetype>");
//
//            sb.append("<Uservalue>");
//            sb.append(sms.getUservalue());
//            sb.append("</Uservalue>");
//
//            sb.append("<Starttime>");
//            sb.append(sms.getStarttime());
//            sb.append("</Starttime>");
//
//            sb.append("<Endtime>");
//            sb.append(sms.getEndtime());
//            sb.append("</Endtime>");
//
//            sb.append("<UseIp>");
//            sb.append(sms.getUseIp());
//            sb.append("</UseIp>");
//
//            sb.append("</post>");
//            sb.append("</record>");
//            sb.append("</item>");
//            fos.write(sb.toString().getBytes());
//            fos.close();
            //Thread.sleep(1000);
//            String info = sb.toString();
//                    URLEncoder.encode(info,"UTF-8");
//            Log.i("zxy", "sb.toString()" +info);

            if(NetUtil.isNetworkAvailable(FileActivity.this)){
                SendInfo.upInfo(upInfo,FileActivity.this);
            }else{
                upInfo.save();
                pm.putBoolean("isInfoSave",true);
                Log.i("zxy", "upInfo.save()=" +upInfo.getAllInfo());
//              pm.putBoolean("isUpload",false);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static String getHostIP() {

        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            Log.i("yao", "SocketException");
            e.printStackTrace();
        }
        return hostIp;

    }
}
